#!/bin/bash

# This script activates or starts firefox. It shares all firefox settings with
# another host.
#
# The script is supposed to run either on a 'server' host, $server, or on a
# 'client' host, $client. Server and client differ in that server serves the
# ~/.mozilla directory. The client host mounts it.
#
# If firefox already runs locally, its window is just activated so it pops up
# to the front. No mounting or starting needs to be done. If firefox does not
# run locally, a possibly existing remote firefox window is closed gracefully
# before starting firefox locally.
#

set -e    # <-- do not remove: script assumes exit on first error throughout
set -x

client='EDIT_ME_1'      # hostname of client
server='EDIT_ME_2'      # hostname of server
profiledir='EDIT_ME_3'  # e.g. 'djen3857f.default'
backupdir='EDIT_ME_4'   # some dir on client

me=$(hostname)
bookmarks="$HOME/.mozilla/firefox/$profiledir/bookmarks.html"

case $me in

   $client)
      if ! `DISPLAY=:0 wmctrl -a firefox` ; then
         ssh $server 'DISPLAY=:0 wmctrl -c firefox' || true
         sshfs -o rw,nonempty $server:$HOME/.mozilla $HOME/.mozilla
         DISPLAY=:0 /usr/local/bin/firefox "$@"
         cp $bookmarks $backupdir
         fusermount -q -u $HOME/.mozilla
      fi
      ;;
   
   $server)
      if ! `DISPLAY=:0 wmctrl -a firefox` ; then
         ssh $client 'DISPLAY=:0 wmctrl -c firefox' || true
         ssh $client 'while `mountpoint -q .mozilla` ; do sleep 1 ; done' || true
         DISPLAY=:0 /usr/local/bin/firefox "$@"
         scp $bookmarks $client:$backupdir
      fi
      ;;

   *)
      echo "I ($me) am neither $client nor $server. Exit."
      exit 1
      ;;

esac

# vim:tw=0
